﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JwtDemo.Services
{

    public class JwtService
    {
        public JwtService(string sign, string audience, string issuer)
        {
            Sign = sign;
            Audience = audience;
            Issuer = issuer;
        }
        /// <summary>
        /// 过期时间，分
        /// </summary>
        public int TokenExpires { get; set; }
        public int RefreshTokenExpires { get; set; }
        public string Sign { get; set; }
        public string Audience { get; set; }
        public string Issuer { get; set; }
        public List<Claim>? Claims { get; set; }

        /// <summary>
        /// 生成jwt token
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roles">角色</param>
        /// <returns></returns>
        public string GetToken(string id, List<string> roles)
        {
            SymmetricSecurityKey signingKey = new(Encoding.UTF8.GetBytes(Sign));
            SigningCredentials signingCredentials = new(signingKey, SecurityAlgorithms.HmacSha256);
            List<Claim> _claims = new List<Claim>() { new Claim(ClaimTypes.NameIdentifier, id) };
            if (roles.Count != 0)
            {
                foreach (string role in roles)
                {
                    _claims.Add(new Claim(ClaimTypes.Role, role));
                }
            }
            if (Claims != null && Claims.Count != 0)
            {
                _claims.AddRange(Claims);
            }
            JwtSecurityToken jwt = new(Issuer, Audience, _claims,
                expires: DateTime.UtcNow.AddMinutes(TokenExpires),
                signingCredentials: signingCredentials);
            string encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            return encodedJwt;
        }
    }
}
